public class Philosopher implements Runnable{
	
	private Thread t;
	protected Table table;
	protected int id_left, id_right;
	protected int id;
	protected Semaphore semaphore;

	public Philosopher (int newId, Table newTable, Semaphore newSemaphore){
		this.id= newId;
		this.table= newTable;
		this.semaphore = newSemaphore;

		id_left = table.left_fork(id);
		id_right = table.right_fork(id);

		t= new Thread(this);
		t.start();
	}


	protected void think(){
		try{
			System.out.println ("Philosopher " + id + " thinking");
			int delay= (int)(Math.random()*10);
			t.sleep(delay);
			System.out.println ("Philosopher " + id + " stop thinking");
		} catch (InterruptedException e) {}
	}

	protected void eat(){
		try{
			System.out.println ("Philosopher " + id + " eating");
			int delay= (int)(Math.random()*10);
			t.sleep(delay);
			System.out.println ("Philosopher " + id + " stop eating");
		} catch (InterruptedException e) {}
	}

	protected void begin_process(){
		Fork tizq= table.fork(id_left);
		Fork tder= table.fork(id_right);
		try{
			semaphore.P(id);
			
			while (tizq.isPicked()) {
				System.out.println("Philosopher " + id + " tried to get the left fork but it wasnt available");
				t.sleep((long) (Math.random()*1000));
			}
			tizq.pick();
			System.out.println("Philosopher " + id + " picked up the left fork: "+tizq.getId());
			t.sleep((long) (Math.random()*1000));
			while (tder.isPicked()) {
				System.out.println("Philosopher " + id + " tried to get the right fork but it wasnt available");
				t.sleep((long) (Math.random()*1000));
			}
			tder.pick();
			System.out.println("Philosopher " + id + " picked up the right fork: "+tder.getId());
			t.sleep((long) (Math.random()*1000));
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}

	protected void finish_process(){
		Fork tizq= table.fork(id_left);
		Fork tder= table.fork(id_right);
		tizq.release();
		tder.release();
		semaphore.V(id);
	}

	public void run(){
		while (true){
			think();
			begin_process();
			eat();
			finish_process();
		}
	}
}

